from django.contrib import admin
from .models import User, FoodCategory, Food, FoodImage, FoodSpec, CartItem, Order, OrderItem, Address
from django.urls import path
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.utils import timezone
from django.utils.html import format_html

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('id', 'username', 'openid', 'phone', 'date_joined')
    search_fields = ('username', 'openid', 'phone')
    list_filter = ('date_joined',)


@admin.register(FoodCategory)
class FoodCategoryAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'sort_order', 'is_active', 'created_at')
    list_filter = ('is_active',)
    search_fields = ('name',)
    list_editable = ('sort_order', 'is_active')


class FoodImageInline(admin.TabularInline):
    model = FoodImage
    extra = 1


class FoodSpecInline(admin.TabularInline):
    model = FoodSpec
    extra = 1


@admin.register(Food)
class FoodAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'category', 'price', 'sold', 'is_hot', 'is_new', 'is_active')
    list_filter = ('category', 'is_hot', 'is_new', 'is_active')
    search_fields = ('name', 'description')
    list_editable = ('price', 'is_hot', 'is_new', 'is_active')
    inlines = [FoodSpecInline, FoodImageInline]


@admin.register(CartItem)
class CartItemAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'food', 'spec', 'count', 'is_checked', 'updated_at')
    list_filter = ('is_checked', 'updated_at')
    search_fields = ('user__username', 'food__name')


class OrderItemInline(admin.TabularInline):
    model = OrderItem
    extra = 0
    readonly_fields = ('food', 'food_name', 'food_image', 'food_price', 'spec', 'count', 'total_price')
    fields = ('food', 'food_name', 'spec', 'food_price', 'count', 'total_price')
    can_delete = False
    
    def total_price(self, obj):
        return f"{obj.food_price * obj.count:.2f}元"
    total_price.short_description = "小计"


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('id', 'order_number', 'user', 'status', 'total_price', 'created_at')
    list_filter = ('status', 'created_at', 'paid_at', 'delivered_at', 'finished_at')
    search_fields = ('order_number', 'user__username', 'user__nickname')
    readonly_fields = (
        'order_number', 'created_at', 'updated_at', 
        'paid_at', 'delivered_at', 'finished_at'
    )
    raw_id_fields = ('user', 'address')
    inlines = [OrderItemInline]


@admin.register(Address)
class AddressAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'name', 'phone', 'province', 'city', 'is_default')
    list_filter = ('is_default', 'province', 'city')
    search_fields = ('user__username', 'name', 'phone', 'detail')
